const express = require('express');
const fs = require('fs').promises;
const cors = require('cors')
const path = require('path');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3010;
const MAX_HISTORY_ITEMS = 100;
const DATA_DIR = path.join(__dirname, 'data');
const HISTORY_FILE = path.join(DATA_DIR, 'history.json');
app.use(cors({
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type']
}));
app.use(bodyParser.json({ limit : '50mb'}));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
// 创建数据目录
async function initDataDir() {
    try {
        await fs.access(DATA_DIR);
    } catch (err) {
        await fs.mkdir(DATA_DIR, { recursive: true });
    }
}

// 初始化历史记录文件
async function initHistoryFile() {
    try {
        await fs.access(HISTORY_FILE);
    } catch (err) {
        await fs.writeFile(HISTORY_FILE, JSON.stringify([]));
    }
}

// 加载历史记录
async function loadHistory() {
    try {
        const data = await fs.readFile(HISTORY_FILE, 'utf8');
        return JSON.parse(data);
    } catch (err) {
        console.error('Error loading history:', err);
        return [];
    }
}

// 保存历史记录
async function saveHistory(history) {
    try {
        await fs.writeFile(HISTORY_FILE, JSON.stringify(history));
    } catch (err) {
        console.error('Error saving history:', err);
    }
}

// 清理过期记录（修改后的版本）
async function cleanupExpiredRecords(history = null) {
    // 如果没有提供历史记录，则加载它
    if (!history) {
        history = await loadHistory();
    }

    const now = Date.now();
    const twentyFourHours = 24 * 60 * 60 * 1000;

    // 过滤掉超过24小时的记录
    const validRecords = history.filter(item => now - item.timestamp < twentyFourHours);

    let needsUpdate = validRecords.length !== history.length;

    // 确保不超过最大记录数
    if (validRecords.length > MAX_HISTORY_ITEMS) {
        const trimmedRecords = validRecords.slice(-MAX_HISTORY_ITEMS);
        await saveHistory(trimmedRecords);
        console.log(`修剪历史记录，保留最新的 ${MAX_HISTORY_ITEMS} 条`);
        needsUpdate = true;
    }

    if (needsUpdate) {
        await saveHistory(validRecords);
        console.log(`清理了 ${history.length - validRecords.length} 条过期记录`);
    }

    return validRecords;
}

// 设置定时清理任务（每小时执行一次）
function scheduleCleanup() {
    setInterval(cleanupExpiredRecords, 60 * 60 * 1000);
    console.log('定时清理任务已启动');
}

// 初始化应用
async function initApp() {
    await initDataDir();
    await initHistoryFile();
    await cleanupExpiredRecords();
    scheduleCleanup();
}

// 启动应用
initApp().then(() => {
    // 中间件
    app.use(express.json());
    app.use(express.static(path.join(__dirname, 'public')));

    // 保存内容
    app.post('/save', async (req, res) => {
        try {
            const { content } = req.body;

            if (!content) {
                return res.status(400).json({ success: false, message: '内容不能为空' });
            }

            // 生成唯一ID
            const id = crypto.randomBytes(16).toString('hex');
            const timestamp = Date.now();

            // 创建文本文件
            const filePath = path.join(DATA_DIR, `${id}.txt`);
            await fs.writeFile(filePath, content);

            // 更新历史记录
            const history = await loadHistory();
            history.push({ id, timestamp });
            await saveHistory(history);

            // 清理过期记录并限制数量
            await cleanupExpiredRecords();

            res.json({ success: true });
        } catch (err) {
            console.error('Error saving content:', err);
            res.status(500).json({ success: false, message: '保存失败' });
        }
    });

    // 获取历史记录列表
    app.get('/history', async (req, res) => {
        try {
            const history = await loadHistory();

            // 按时间戳降序排序（最新的在前）
            const sortedHistory = [...history].sort((a, b) => b.timestamp - a.timestamp);

            // 为每条记录获取前200个字符作为预览
            const historyWithPreviews = [];

            for (const item of sortedHistory) {
                try {
                    const filePath = path.join(DATA_DIR, `${item.id}.txt`);
                    const content = await fs.readFile(filePath, 'utf8');
                    historyWithPreviews.push({ ...item, content });
                } catch (err) {
                    console.error(`Error reading file ${item.id}.txt:`, err);
                    // 如果文件不存在，跳过此记录
                }
            }

            res.json({ success: true, history: historyWithPreviews });
        } catch (err) {
            console.error('Error getting history:', err);
            res.status(500).json({ success: false, message: '获取历史记录失败' });
        }
    });

    // 获取单条历史记录
    app.get('/history/:id', async (req, res) => {
        try {
            const { id } = req.params;
            const filePath = path.join(DATA_DIR, `${id}.txt`);

            const content = await fs.readFile(filePath, 'utf8');
            res.json({ success: true, content });
        } catch (err) {
            console.error('Error getting history item:', err);
            res.status(404).json({ success: false, message: '历史记录不存在' });
        }
    });

    // 删除单条历史记录
    app.delete('/history_delete/:id', async (req, res) => {
        res.setHeader('Access-Control-Allow-Methods', 'DELETE');
        try {
            const { id } = req.params;
            const filePath = path.join(DATA_DIR, `${id}.txt`);

            // 删除文件
            await fs.unlink(filePath);

            // 更新历史记录
            let history = await loadHistory();
            history = history.filter(item => item.id !== id);
            await saveHistory(history);

            res.json({ success: true });
        } catch (err) {
            console.error('Error deleting history item:', err);
            res.status(500).json({ success: false, message: '删除失败' });
        }
    });

    // 删除所有历史记录
    app.delete('/history', async (req, res) => {
        try {
            const history = await loadHistory();

            // 删除所有文件
            for (const item of history) {
                try {
                    const filePath = path.join(DATA_DIR, `${item.id}.txt`);
                    await fs.unlink(filePath);
                } catch (err) {
                    console.error(`Error deleting file ${item.id}.txt:`, err);
                }
            }

            // 清空历史记录
            await saveHistory([]);

            res.json({ success: true });
        } catch (err) {
            console.error('Error deleting all history:', err);
            res.status(500).json({ success: false, message: '清空失败' });
        }
    });

    // 启动服务器
    app.listen(PORT, () => {
        console.log(`服务器运行在 http://localhost:${PORT}`);
    });
}).catch(err => {
    console.error('Error initializing app:', err);
});
